using Digitalmes.Domain.Entities.Mes.Reworks;

namespace Digitalmes.Application.Mes.Reworks.Doc.Queries;

/// <summary>
/// 在线返未完成的工单信息分页查询命令。
/// </summary>
public sealed record GetOnlineDoingReworkDocListWithPagedQuery(
    string? Sn,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ReworkDocDto>>>;

internal sealed class GetOnlineDoingReworkDocListWithPagedQueryHandler(IRepository<ReworkDoc> repo)
    : IRequestHandler<GetOnlineDoingReworkDocListWithPagedQuery, IResult<PagedList<ReworkDocDto>>>
{
    public async Task<IResult<PagedList<ReworkDocDto>>> Handle(GetOnlineDoingReworkDocListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(m => m.Defects)
            .WhereIF(!string.IsNullOrEmpty(request.Sn), m => m.Sn == request.Sn)
            .Where(m => m.ReworkMode == ReworkModeEnum.Online)
            .Where(m => m.Status == ReworkStatusEnum.Created || m.Status == ReworkStatusEnum.Reworking)
            .OrderByDescending(m => m.Id)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ReworkDocDto>>());
    }
}
